<?php

namespace App\Http\Controllers\Manger;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Chanjet\TplusCommonController;
use App\Http\Validate\Manger\Manger as ValidateMangerManger;
use App\Models\Admin\AdminUser;
use App\Models\CompanyUserDinding;
use App\Models\Manger\Manger;
use App\Models\Manger\Mangerrule;
use App\Models\Warehouse\WarehouseList;
use App\Services\Chanjet\ChanjetRequest;
use App\Services\Common\Common;
use App\Services\Manger\MangerAccount;
use App\Services\Stock\Stock;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class MangerController extends BaseController
{

    /**
     * 各端管理员列表
     */
    public function getlist(Request $request)
    {
        // MangerAccount::setMangerRule(1,1);exit;
        $utype = $request->utype ?? 0;
        $status = $request->status ?? 0;
        $isgetall = $request->isgetall ?? 0;
        // if (!in_array($utype, [2, 3, 4, 5, 6, 7, 8])) {
        //     return response()->json(['code' => '001', 'msg' => getMsgByCode('001')]);
        // }
        $list = MangerAccount::getMangerList($request, $this->mangerinfo['cpid'], $utype, $status, $isgetall);
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 新增管理员
     */

    public function dopostadd(Request $request)
    {
        // $utype = $request->utype ?? 2;

        $utypes = is_array($request->utypes) ? $request->utypes : (is_array(json_decode($request->utypes, true)) ? json_decode($request->utypes, true) : []);
        $utypes = array_unique($utypes);


        foreach ($utypes as $utype) {
            if (!in_array($utype, [2, 3, 4, 5, 6, 7, 8])) {
                return response()->json(['code' => '001', 'msg' => '无效角色参数']);
            }
        }

        if (count($utypes) <= 0) {
            return response()->json(['code' => '001', 'msg' => '请选择角色']);
        }




        $req_data = $request->only(['code_no', 'username', 'mobile', 'realname', 'cpd_user_id', 'sys_dpm_id']);

        $Validate = new ValidateMangerManger;
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $isexist = Manger::where([['code_no', $req_data['code_no']], ['cpid', $this->mangerinfo['cpid']]])
            ->orWhere([['username', $req_data['username']], ['cpid', $this->mangerinfo['cpid']]])
            ->orWhere([['mobile', $req_data['mobile']], ['cpid', $this->mangerinfo['cpid']]])
            ->orWhere([['realname', $req_data['realname']], ['cpid', $this->mangerinfo['cpid']]])
            ->first();

        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '用户编码、用户名、手机号、姓名不允许重复']);
        }


        //判断账套信息是否包含超管信息

        $isexist = AdminUser::where([['username', $req_data['username']]])->first();

        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '管理员信息不可与超管信息相同']);
        }


        $data = [
            'cpid' => $this->mangerinfo['cpid'],
            'pid' => $this->mangerinfo['id'],
            'code_no' => $req_data['code_no'],
            'username' => $req_data['username'],
            'mobile' => $req_data['mobile'],
            'realname' => $req_data['realname'],
            // 'utype' => $utype,
            'utypes' => join(',', $utypes),
            // 'cpd_user_id' => $req_data['cpd_user_id'],
            'sys_dpm_id' => $req_data['sys_dpm_id'],
            'update_at' => time()
        ];
        $data['password'] = MD5(MD5('huakun_' . env('MANGER_DEF_PWD')));
        $data['create_at'] = time();
        $manger_id = Manger::create($data)->id;
        //设置默认权限

        foreach ($utypes as $utype) {
            if ($utype == 7) {
                $wdata = [
                    'cpid' => $this->mangerinfo['cpid'],
                    'wtype' => 3,
                    'warehouse_no' => Common::getPinyin($req_data['realname']),
                    'warehouse_name' => $req_data['realname'],
                    'update_at' => time(),
                    'manger_id' => $manger_id
                ];
                $wdata['create_at'] = time();

                DB::beginTransaction();
                try {

                    $insert_id = WarehouseList::create($wdata)->id;
                    //是否需要同步库存增加记录数据

                    Stock::syncStockByWarehouse($insert_id, $wdata, $this->mangerinfo['cpid']);

                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    return response()->json(['code' => '001', 'msg' => '新增失败' . $e->getMessage()]);
                }

            }

            MangerAccount::setMangerRule($manger_id, $utype);
        }
        //如为业务，则创建个人库

        $this->syncMangerWarehouse($req_data,$utypes,'add');


        return response()->json(['code' => '000', 'msg' => '新增成功']);
    }

    /**
     *编辑管理员
     */
    public function dopostedit(Request $request)
    {
        $id = $request->id ?? 0;
        $info = Manger::where([['id', $id], ['cpid', $this->mangerinfo['cpid']], ['status', 1]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }



        $utypes = is_array($request->utypes) ? $request->utypes : (is_array(json_decode($request->utypes, true)) ? json_decode($request->utypes, true) : []);
        $utypes = array_unique($utypes);


        foreach ($utypes as $utype) {
            if (!in_array($utype, [2, 3, 4, 5, 6, 7, 8])) {
                return response()->json(['code' => '001', 'msg' => '无效角色参数']);
            }
        }

        if (count($utypes) <= 0) {
            return response()->json(['code' => '001', 'msg' => '请选择角色']);
        }




        $req_data = $request->only(['mobile', 'realname', 'cpd_user_id', 'sys_dpm_id','username']);

        $Validate = new ValidateMangerManger('edit');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $isexist = Manger::where([['id', '<>', $id], ['cpid', $this->mangerinfo['cpid']]])
            ->where(function ($query) use ($req_data) {
                $query->where('mobile', $req_data['mobile'])
                    ->orWhere('realname', $req_data['realname'])
                    ->orWhere('username', $req_data['username']);
            })
            ->first();

        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '用户名、手机号、姓名不允许重复']);
        }

        $data = [
            'mobile' => $req_data['mobile'],
            'username' => $req_data['username'],
            'realname' => $req_data['realname'],
            // 'cpd_user_id' => $req_data['cpd_user_id'],
            'sys_dpm_id' => $req_data['sys_dpm_id'],
            'utypes' => join(',', $utypes),
            'update_at' => time()
        ];

        DB::beginTransaction();

        Manger::where([['id', $id], ['cpid', $this->mangerinfo['cpid']]])->update($data);


        $ischange_ruletype = 0;
        foreach ($utypes as $utype) {
            if (in_array($utype, explode(',', $info->utypes))) {
                continue;
            } else {
                $ischange_ruletype = 1;
            }


            if ($utype == 7) {
                $wdata = [
                    'cpid' => $this->mangerinfo['cpid'],
                    'wtype' => 3,
                    'warehouse_no' => Common::getPinyin($req_data['realname']),
                    'warehouse_name' => $req_data['realname'],
                    'update_at' => time(),
                    'manger_id' => $id
                ];
                $wdata['create_at'] = time();


                try {

                    $insert_id = WarehouseList::create($wdata)->id;
                    //是否需要同步库存增加记录数据

                    Stock::syncStockByWarehouse($insert_id, $wdata, $this->mangerinfo['cpid']);
                } catch (\Exception $e) {
                    DB::rollBack();
                    return response()->json(['code' => '001', 'msg' => '新增失败' . $e->getMessage()]);
                }
            }

            MangerAccount::setMangerRule($id, $utype);
        }
        DB::commit();

        $ischange_ruletype == 1 && MangerAccount::clearTokenKey($id);

        $this->syncMangerWarehouse(array_merge($req_data,['code_no'=>$info['code_no']]),$utypes,'edit');


        return response()->json(['code' => '000', 'msg' => '编辑成功']);
    }

    /**
     * 冻结
     */
    public function changestatus(Request $request)
    {
        $id = $request->id ?? 0;
        $info = Manger::where([['id', $id], ['cpid', $this->mangerinfo['cpid']]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $status = 2;
        Manger::where([['id', $id]])->update(['status' => $status, 'update_at' => time()]);

        //冻结需删除管理员登录状态
        MangerAccount::clearTokenKey($id);

        //t+ 员工修改
        $Chanjet_param = [
            "dto" => [
                "Code" => $info['code_no'],
                "Disabled" => true
            ]
        ];
        //角色包含销售 属性为业务员
        if(TplusCommonController::isAllowRequestTplus($this->mangerinfo)) {
            ChanjetRequest::getInstance()->personUpdate($Chanjet_param,$this->mangerinfo['org_id']);
        }

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 重置密码
     */
    public function resetpassword(Request $request)
    {
        //重置后需重置账号登陆状态

        $id = $request->id ?? 0;
        $info = Manger::where([['id', $id], ['cpid', $this->mangerinfo['cpid']]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $password = MD5(MD5('huakun_' . env('MANGER_DEF_PWD')));
        Manger::where([['id', $id]])->update(['password' => $password, 'update_at' => time()]);

        //重置后需重置账号登陆状态
        MangerAccount::cleartokenkey($id);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 获取权限
     */

    public function getruleinfo(Request $request)
    {
        //获取菜单列表以及管理员已设置的权限
        $id = $request->id ?? 0;
        $utype = intval($request->utype) ?? 0;
        $info = Manger::where([['id', $id], ['cpid', $this->mangerinfo['cpid']]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($utype > 0) {
            if (!in_array($utype, explode(',', $info->utypes))) {
                return response()->json(['code' => '001', 'msg' => '该用户未拥有该权限']);
            }
        } else {
            $utype = explode(',', $info->utypes)[0];
        }

        $rule_info = Mangerrule::where(['mid' => $id, 'utype' => $utype])->first();

        if (!$rule_info) {
            return response()->json(['code' => '001', 'msg' => '权限信息错误']);
        }



        $ruleinfo = json_decode($rule_info->ruleinfo, true);
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => ['utype' => $utype, 'ruleinfo' => $ruleinfo]]);
    }

    /**
     * 设置权限
     */
    public function dopostrule(Request $request)
    {

        //设置权限后，需要对比用户现有权限
        $id = $request->id ?? 0;
        $utype = intval($request->utype) ?? 0;
        $ruleinfo = is_array($request->ruleinfo) ? $request->ruleinfo : (is_array(json_decode($request->ruleinfo, true)) ? json_decode($request->ruleinfo, true) : []);
        $info = Manger::where([['id', $id], ['cpid', $this->mangerinfo['cpid']]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if (count($ruleinfo) <= 0) {
            return response()->json(['code' => '001', 'msg' => '权限菜单信息有误']);
        }
        if (!in_array($utype, explode(',', $info->utypes))) {
            return response()->json(['code' => '001', 'msg' => '该用户未拥有该权限']);
        }

        $rule_info = json_encode($ruleinfo);
        Mangerrule::where(['mid' => $id, 'utype' => $utype])->update(['ruleinfo' => $rule_info]);

        Redis::set('manger_user_menulist_' . $id . '_' . $utype, $rule_info);
        //重置用户现有权限
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 获取管理信息
     */
    public function getone()
    {
        $mangerinfo = $this->mangerinfo;
        $id = $mangerinfo['id'] ?? 0;
        $one = Manger::where([['id', $id]])->first();
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $one]);
    }


    public function getcpduserlist(Request $request)
    {
        $cpd_id = intval($this->mangerinfo['cpd_id']);

        $list = CompanyUserDinding::where(['cpd_id' => $cpd_id])->get()->toArray();
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => ['list' => $list]]);
    }

    /**
     *  t+同步 员工信息/仓库信息
     *
    */
    public function syncMangerWarehouse($req_data=[],$utypes = [],$operate = 'add'){
        //T+ 员工  utype 7 销售
        $Chanjet_param = [
            "dto" => [
                "Code" => $req_data['code_no'],
                "Name" => $req_data['realname'],
                "MobilePhoneNo" => $req_data['mobile'],
//                "IsSalesMan" => in_array('7',$utypes)?"true":"false",
                "IsSalesMan" => "true",
                "Department" => ["Code"=>$req_data['sys_dpm_id']]
            ]
        ];

        //角色包含销售 属性为业务员
        if($operate == 'add'){
            $requestData = [
                "api" => "personCreate",
                "param" => $Chanjet_param,
                "mangerinfo" => $this->mangerinfo
            ];
            \App\Jobs\Manger::dispatch($requestData);

            //业务员 创建个人仓库
            if(in_array('7',$utypes)){
                $Chanjet_warehouse = [
                    "dto" => [
                        "Code" => Common::getPinyin($req_data['realname']),
                        "Name" => $req_data['realname'],
                    ]
                ];
                $requestData = [
                    "api" => "WarehouseCreate",
                    "param" => $Chanjet_warehouse,
                    "mangerinfo" => $this->mangerinfo
                ];
                \App\Jobs\Manger::dispatch($requestData);
            }
        }
        if($operate == 'edit'){
            $requestData = [
                "api" => "personUpdate",
                "param" => $Chanjet_param,
                "mangerinfo" => $this->mangerinfo
            ];
            \App\Jobs\Manger::dispatch($requestData);
        }
    }
}
